<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/11
 * Time: 16:13
 */

namespace Api\Controller;
use Admin\Model\ConsultingModel;
use Admin\Model\ReplyModel;
use  Common\Lib\Util\LogUtil;

class ConsultingController extends ApiController
{
    private $consult;
    private $reply;
    private $status;
    private $user;
    function __construct() {
        $this->consult =  new ConsultingModel();
        $this->reply =  new ReplyModel();
        $this->status = array('1'=>'未处理','2'=>'已处理','3'=>'已关闭');
        $this->user = M('users');
        parent::__construct();

    }

    public function add() {
        $user_id = I('user_id');
        $content = I('content');
        $title = msubstr($content, 0, 10, "utf-8", false);
        $mobile = I('mobile');
        $qq = I('qq');

        if (!$user_id || !$content || (!$mobile && !$qq)) {
            return $this->callBack("无效的参数！",$this->ERROR_CODE);
        }

        $data = array(
            'title' => $title,
            'content'=> $content,
            'consult_id'=> $user_id,
            'consult_time'=> time(),
            'mobile' => $mobile,
            'qq' => $qq
        );
        $rs = $this->consult->add($data);

        if ($rs !== false) {
            return $this->callBack("咨询成功！",$this->SUCCESS_CODE);
        }
        return $this->callBack("咨询失败！",$this->ERROR_CODE);
    }

    /**
     * @todo 资讯列表
     * @param int $type
     * @param int $limit  获取条数
     */
    public function getConsultList(){
        $curPage = I('p',1);
        $where = array(
            'consult_id' => session('userId'),
        );
        $result =  $this->consult->getApiConsulList($where,$curPage,6);
        $data['data'] = $result;
        $data['curPage'] = $curPage+1;
        $data['totalPage'] = $result['totalPage'];
        return $this->callBack("资讯列表",$this->SUCCESS_CODE,$data);
    }

    public function doAdd() {
        $userId = session('userId');
        $title = $_POST['title'];
        $content = $_POST['content'];

        if (!$userId || !$title || !$content) {
            return $this->callBack("无效的参数！",$this->ERROR_CODE);
        }

        $data = array(
            'title' => $title,
            'content'=> $content,
            'consult_id'=> $userId,
            'consult_time'=> time(),
             'status'=> 1
        );
        $rs = $this->consult->add($data);

        if ($rs !== false) {
            $res= $this->consult->where(array('id' => $rs))->find();
            $this->sendConsultNotice($res);//发送咨询通知
            $this->sendManageNotice($res);//给工作管理员发送咨询通知
            return $this->callBack("咨询成功！",$this->SUCCESS_CODE);
        }
        return $this->callBack("咨询失败！",$this->ERROR_CODE);
    }
    public function doReply() {
        $userId = session('userId');//回复人
        $content = I('content');//回复内容
        $consultId = I('consult_id');//咨询Id
        if (!$userId||!$content) {
            return $this->callBack("无效的参数！",$this->ERROR_CODE);
        }
        $data = array(
            'content'=> $content,
            'reply_id'=> $userId,
            'consult_id'=>$consultId,
            'reply_time'=> time(),//回复时间
            'status'=> 1

        );
        $rs = $this->reply->add($data);
        if ($rs !== false) {
            $res ['content'] = $content;
            $res['replyName'] = getUserName($userId);
            $res['avatar'] = getAvatar($userId);
            $res['reply_time'] = time();
            return $this->callBack('回复成功！',$this->SUCCESS_CODE,$res);
        }
        return $this->callBack("回复失败！",$this->ERROR_CODE);
    }

    //发送咨询处理通知
    private function sendConsultNotice($res) {
        $toUser = session('openId');
        vendor('WeiXinSDK.wechat','','.class.php');
        $options = array(
            'appid' => C('appId'),
            'appsecret' => C('appSecret')
        );
        $weObj = new \Wechat($options);
        $data = array(
            //接收者openid
            'touser' => $toUser,
            //模板ID
            'template_id' => C('WEIXIN_TEMPLATE_CONSULT_HANDLE'),
            //模板跳转链接，不填则不用跳转
            'url' => '',
            //模板数据
            'data' => array(
                'first' => array('value' => sprintf('[%s]咨询处理的进度。',$res['title']),'color' => '#173177'),
                //咨询人
                'keyword1' => array('value' => sprintf('%s',getUserName($res['consult_id'])),'color' => '#173177'),
                //咨询title
                'keyword2' => array('value' => sprintf('%s',$res['title']),'color' => '#173177'),
                //咨询时间
                'keyword3' => array('value' => date('Y-m-d H：i：s',$res['consult_time']),'color' => '#173177'),
                //咨询状态
                'keyword4' => array('value' => sprintf('%s',$this->status[$res['status']]),'color' => '#173177'),
                //备注
                'remark' => array('value' => '感谢你的使用。','color' => '#173177')
            )
        );
        $result = $weObj->sendTemplateMessage($data);
        $userType = '普通用户';
        LogUtil::info(sprintf('发送咨询通知！接收方用户类型：%s',$userType));
        if (is_array($result)) {
            $result['consultingId'] = $res['id'];
            $result['toUser'] = $toUser;
            $result['userType'] = $userType;
            LogUtil::info($result);
        } else {
            LogUtil::info(sprintf('咨询id : %s , openId : %s , 用户类型 : %s , 信息 : %s', $res['id'], $toUser, $userType, $weObj->errMsg));
        }
        return $result;
    }

//给工作人员发送咨询处理通知
    private function sendManageNotice($res) {
        vendor('WeiXinSDK.wechat','','.class.php');
        $options = array(
            'appid' => C('appId'),
            'appsecret' => C('appSecret')
        );
        $weObj = new \Wechat($options);
        $role_id = C('EMPLOYEE_ROLE_ID');
        $where['role_id'] = array('eq',$role_id);
        $where['openid'] = array('neq','');
        $tousers = $this->user->where($where)->select();
        if(!empty($tousers)){
            foreach ($tousers as $value){
                $data = array(
                    //接收者openid
                    'touser' => $value['openid'],
                    //模板ID
                    'template_id' => C('WEIXIN_TEMPLATE_CONSULT_HANDLE'),
                    //模板跳转链接，不填则不用跳转
                    'url' => '',
                    //模板数据
                    'data' => array(
                        'first' => array('value' => sprintf('[%s]咨询处理的进度。',$res['title']),'color' => '#173177'),
                        //咨询人
                        'keyword1' => array('value' => sprintf('%s',getUserName($res['consult_id'])),'color' => '#173177'),
                        //咨询title
                        'keyword2' => array('value' => sprintf('%s',$res['title']),'color' => '#173177'),
                        //咨询时间
                        'keyword3' => array('value' => date('Y-m-d H：i：s',$res['consult_time']),'color' => '#173177'),
                        //咨询状态
                        'keyword4' => array('value' => sprintf('%s',$this->status[$res['status']]),'color' => '#173177'),
                        //备注
                        'remark' => array('value' => '感谢你的使用。','color' => '#173177')
                    )
                );
                $result = $weObj->sendTemplateMessage($data);
                $userType = '工作人员';
                LogUtil::info(sprintf('发送咨询通知！接收方用户类型：%s',$userType));
                if (is_array($result)) {
                    $result['consultingId'] = $res['id'];
                    $result['toUser'] = $value['openid'];
                    $result['userType'] = $userType;
                    LogUtil::info($result);
                } else {
                    LogUtil::info(sprintf('咨询id : %s , openId : %s , 用户类型 : %s , 信息 : %s', $res['id'], $value['openid'], $userType, $weObj->errMsg));
                }
            }
        }
    }

}